package com.develope.tree.service;

import org.ksoap2.serialization.PropertyInfo;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import com.develope.tree.BaseApplication;
import com.develope.tree.Logger;
import com.develope.tree.UserParcel;
import com.develope.tree.db.dbUserParcel;
import com.develope.tree.utils.Alerts;
import com.develope.tree.utils.Utils;

public class MyService extends Service{
	private final IBinder mBinder = new MyBinder();
	dbUserParcel userdb;
	@Override
	 public int onStartCommand(Intent intent, int flags, int startId){
		if(Utils.isEnableNetwork()){
//			sampleCallSOAP();
		}
		return Service.START_STICKY;		 
	 }
	
	public IBinder onBind(Intent arg0) {
	    return mBinder;
	  }
	
	public class MyBinder extends Binder {
	    public MyService getService() {
	      return MyService.this;
	    }
	  }
	
	public void onDestroy(){
		super.onDestroy();
		BaseApplication.makeToastMsg("service detroyed");
	}
	
	private void sampleCallSOAP() {
		
		PropertyInfo proInfo = new PropertyInfo();
		proInfo.setName("UserName");
		proInfo.setValue("admin");
		proInfo.setType(String.class);
		
		HttpHandler httpHandler = new HttpHandler(SoapHelper.METHOD_GetUserParcels, proInfo){
			@Override
			public void onResponse(int errorCode, String result) {
				
				Alerts.hideLoadingDialog();
				Logger.error("[onResponse] errorCode:" + errorCode);
				
				BaseApplication.makeToastMsg("[onResponse] result:" + result);
				
				if (TextUtils.isEmpty(result) || !result.contains(";")) {
					Log.d("ERROR", "Get user information failed. Please try again!");
					return;
				}
				String[] rows = result.split(";");
				if (rows == null)
					return;
				for (int i = 0; i < rows.length; i++) {
					String[] cols = rows[i].split(":");
					
					UserParcel up = new UserParcel();
					up.setParcelID(Integer.parseInt(cols[0]));
					up.setParcelName(cols[1]);
					
					userdb.insertUser(up);
					
				}
				
			}
		};
		httpHandler.execute();
	}	
	
}
